# -*- coding: utf-8 -*-
'''
Copyright(C) 2013 "Kevin Xu <ssonxu@gmail.com>"

This file is part of acqu-center.

acqu-center is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

acqu-center is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with acqu-center.  If not, see <http://www.gnu.org/licenses/>.
'''
import webapp2
from modules.Predef import Predef as PRE
from modules.box import Box
from modules.contact import Contact as Con

from google.appengine.api import mail
from google.appengine.api import xmpp

class CronHandler(webapp2.RequestHandler):

    def get(self):
        Box.rockMe()
        self.notify()

    def notify(self):
        query = Con.query().fetch()
        for user in query:
            co=[]
            for s in user.subs:
                b = Box.getBoxByID(s)
                if( b is not None and b in Box.listBoxes(Running=True) ):
                    r=b.report()
                    if r is not None and len(r)>0:
                        co.append(r)
            if len(co)>0:
                self.send( '\n\n'.join(co), user )



    def send(self, s, user):

        result = xmpp.send_message(
                user.xmpp,
                s)

        if result!=xmpp.NO_ERROR:
            logging.info("xmpp send error:")
            mail.send_mail(PRE.sender_,Pre.bare_jid(user.xmpp),PRE.topic_,s)


app = webapp2.WSGIApplication([(r'/cron/.*', CronHandler)], debug=True)
